home *** CD-ROM | disk | FTP | other *** search
/ OpenGL Superbible (2nd Edition) / OpenGL SuperBible e2.iso / tools / FLTK-1.0.6 / test / fromdos.c < prev    next >
Encoding:
C/C++ Source or Header  |  1998-10-06  |  1.5 KB  |  66 lines

  1. /* fromdos.c : strip the stupid ^M characters without mistakes! */
  2.  
  3. /* this can do in-place conversion or be used as a pipe... */
  4.  
  5. #include <stdio.h>
  6. #include <errno.h>
  7. #include <unistd.h>
  8. #include <string.h>
  9.  
  10. int main(int argc, char** argv) {
  11.   int f,c;
  12.   if (argc <= 1) {
  13.     if (isatty(0)) {
  14.       fprintf(stderr,"usage : %s <files>\nStrips ^M characters.\nCan do in-place conversion of many files or can be used in a pipe\n",argv[0]);
  15.       return 1;
  16.     }
  17.     for (;;) {
  18.       c = getchar();
  19.       while (c == '\r') {
  20.     c = getchar();
  21.     if (c != '\n') putchar(c);
  22.       }
  23.       if (c < 0) break;
  24.       putchar(c);
  25.     }
  26.     return 0;
  27.   }
  28.   for (f = 1; f < argc; f++) {
  29.     char* fname = argv[f];
  30.     char tempname[1024];
  31.     FILE* in = fopen(fname,"rb");
  32.     FILE* out;
  33.     int mod = 0;
  34.     if (!in) {
  35.       fprintf(stderr,"%s : %s\n", fname, strerror(errno));
  36.       return 1;
  37.     }
  38.     strcpy(tempname, fname);
  39.     strcat(tempname, ".temp");
  40.     out = fopen(tempname, "wb");
  41.     if (!out) {
  42.       fprintf(stderr,"%s : %s\n", fname, strerror(errno));
  43.       return 1;
  44.     }
  45.     for (;;) {
  46.       c = getc(in);
  47.       while (c == '\r') {
  48.     c = getc(in);
  49.     if (c == '\n') mod=1; else putc(c,out);
  50.       }
  51.       if (c < 0) break;
  52.       putc(c,out);
  53.     }
  54.     fclose(in);
  55.     fclose(out);
  56.     if (!mod) {
  57.       fprintf(stderr,"%s : no change\n", fname);
  58.       unlink(tempname);
  59.     } else if (rename(tempname, fname)) {
  60.       fprintf(stderr,"Can't mv %s %s : %s\n",tempname,fname,strerror(errno));
  61.       return 1;
  62.     }
  63.   }
  64.   return 0;
  65. }
  66.